﻿using System.IO;

using iTextSharp.text;
using iTextSharp.text.pdf;

namespace Utility
{
    public class PDFMerge
    {
        public static PDFMerge Instance = new PDFMerge();

        /// <summary>
        /// PDF合并
        /// </summary>
        /// <param name="fileList">需要合并的PDF文件夹路径</param>
        /// <param name="outMergeFile">合并保存输出路径</param>
        public void mergePDFFiles(string files, string outMergeFile, ref bool status)
        {
            if (File.Exists(outMergeFile))
            {
                File.Delete(outMergeFile);
            }
            string path = outMergeFile.Substring(0, outMergeFile.LastIndexOf("/") + 1);
            if (!Directory.Exists(path))
                Directory.CreateDirectory(path);
            Document document = new Document();
            try
            {
                PdfReader reader;
                PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(outMergeFile, FileMode.Create));
                document.Open();
                PdfContentByte cb = writer.DirectContent;
                PdfImportedPage newPage;
                string[] fileList = files.Split(',');
                for (int i = 0; i <= fileList.Length - 1; i++)
                {
                    if (fileList[i] == outMergeFile)
                        continue;
                    if (!File.Exists(fileList[i]))
                        continue;

                    reader = new PdfReader(fileList[i]);
                    int iPageNum = reader.NumberOfPages;
                    for (int j = 1; j <= iPageNum; j++)
                    {
                        document.NewPage();
                        newPage = writer.GetImportedPage(reader, j);
                        cb.AddTemplate(newPage, 0, 0);
                    }

                    if (iPageNum % 2 != 0)
                    {
                        document.NewPage();
                        cb.NewlineText();
                    }
                }
                document.Close();
            }
            catch
            {
                status = false;
                document.Close();
            }
            status = true;
        }
    }
}